#!/bin/bash

localContainerName=$1
remoteImageName=$2
serviceName=$3
servicePort=$4
containerPort=$5

echo "容器名:$localContainerName 镜像:$remoteImageName 服务:$serviceName"
if [[ -n $(docker ps -q -f "name=$localContainerName") ]]
  then
    # 停止容器
    if [ $(docker inspect --format '{{.State.Running}}' "$localContainerName") ]
      then docker stop "$localContainerName"
      echo "停止容器:$localContainerName"
    fi
    # 删除容器
    docker rm "$localContainerName"
    echo "删除容器:$localContainerName"
fi
# 删除镜像
if [ $(docker image ls "$remoteImageName" | wc -l) -eq 2 ]
  then docker rmi "$remoteImageName"
  echo "删除镜像:$remoteImageName"
fi

docker pull "$remoteImageName"
docker run -itd --privileged=true --restart=always --name "$localContainerName" -p "$servicePort:$containerPort" "$remoteImageName" /sbin/init
docker exec "$localContainerName" systemctl enable "$serviceName"
docker exec "$localContainerName" systemctl start "$serviceName"
